package com.qts.crm.task;

import com.alibaba.boot.dubbo.annotation.DubboConsumer;
import com.qts.crm.company.api.model.CompanyAlert;
import com.qts.crm.company.api.service.CompanyAlertService;
import com.qts.crm.company.api.service.CompanyService;
import com.qts.crm.constant.CompanyConstant;
import com.qts.crm.dto.HandleHistoryDTO;
import com.qts.crm.dto.ResultSupport;
import com.qts.crm.mate.api.service.IMateService;
import com.qts.crm.mate.api.service.IOrgService;
import com.qts.crm.util.OkHttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

/**
 * 定时器
 * Created by qucheng on 17/7/11.
 */
@Component
public class CompanyAlertTimeTask {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @DubboConsumer(version = "1.0.0")
    private IOrgService orgService;

    @DubboConsumer(version = "1.0.0")
    private CompanyService companyService;

    @DubboConsumer(version = "1.0.0")
    private CompanyAlertService companyAlertService;

    @DubboConsumer(version = "1.0.0")
    private IMateService iMateService;

    @Value("${auditHistoryUrl}")
    private String crmUrl;


    @Scheduled(cron = "0 0 1 * * ?") // 定时时间 1 点 更新预警天数
    public void alertTimeTask() {
        //1.查询计时开关是否打开
        try {
            String timeStatus = getOrgMeta(CompanyConstant.COMPANY_TIME_SWITCH);//0开 1关
            if ("1".equals(timeStatus)) {
                logger.warn("计时开关关闭,停止计时");
                return;
            }
            //2 将出未签单有归属剩余天数大于1的记录天数减1
            int count = companyAlertService.updateUnSignCompaniesLeftDays();
            logger.warn("执行了" + count + "条记录");
        } catch (Exception e) {
            logger.error("调用远程接口超时");
        }
    }

    /**
     * 踢出预警客户
     */
    @Scheduled(cron = "0 0 2 * * ?") // 定时时间 2点
    public void shotOffTimeTask() {
        //1.查询计时开关是否打开
        try {
            String timeStatus = getOrgMeta(CompanyConstant.COMPANY_TIME_SWITCH);//0开 1关
            if ("1".equals(timeStatus)) {
                logger.warn("计时开关关闭,停止计时");
                return;
            }
            //2.查询已经超出预警时间线的客户
            List<CompanyAlert> alertCompanies = companyAlertService.getOuterCompaniesWithShotOff();
            //3.遍历 踢出个人仓库
            //时间到了之后踢出公海
            for (CompanyAlert companyAlert : alertCompanies) {
                Long companyId = companyAlert.getCompanyId();
                // 1.库容加一
                if (!iMateService.updateCompanys(companyAlert.getOwner(), 1).isSuccess()) {
                    logger.error("更新库容失败");
                }
                // 2.记录踢出公海操作
                Integer type = 0;
                Integer contactLeftDays = companyAlert.getContactLeftDays();
                Integer signLeftDays = companyAlert.getSignLeftDays();
                if (contactLeftDays <= 0) {
                    type = CompanyConstant.UN_CONTACT_OUT_TYPE;
                } else if (signLeftDays <= 0) {
                    type = CompanyConstant.UN_SIGN_OUT_TYPE;
                }
                HandleHistoryDTO handleHistoryDTO = new HandleHistoryDTO(companyId, 1L, companyAlert.getOwner(), type);
                try {
                    String url = crmUrl + "/crm/handleHistory/saveHandleHistory";
                    ResultSupport result = OkHttpUtils.postRequest(url, handleHistoryDTO);
                    if (!result.getSuccess()) {
                        logger.error("保存客户更改记录失败");
                    }
                } catch (IOException e) {
                    logger.error("调用保存客户更改记录失败");
                }
            }
        } catch (Exception e) {
            logger.error("调用接口超时");
        }
    }

    /**
     * 签单定时器
     */
//    @Scheduled(cron = "0/10 * * * * ?") //todo 定时时间
    public void signBillTimeTask() {
        //1.保存购买记录

        //2.修改签单状态

        //3.踢出预警表

        //4.
    }


    /**
     * 获取组织规则
     * @param key key值
     * @return value
     */
    private String getOrgMeta(String key) {
        return orgService.getOrgMateByOrgIdAndName(1L, key).getModule().getValue();
    }

}
